// 导航守卫
import router from '@/router/index.js'
import store from '@/store/index.js'
// 导入进度条
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { cancelAll } from '@/utils/request.js'

// 白名单
const pageArr = ['/login', '/404']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  Nprogress.start()
  // 取消上个页面所有未完成的请求
  cancelAll()
  if (store.getters.token) {
    if (to.path.toLowerCase() === '/login') {
      next('/')
    } else {
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/getUserInfo')
        next(to.fullPath)
      }
      next()
    }
  } else {
    if (pageArr.includes(to.path.toLowerCase())) {
      next()
    } else {
      // 编码
      next('/login?redirect=' + encodeURIComponent(to.fullPath))
    }
  }
  Nprogress.done()
})
// 后置守卫
router.afterEach((to, from) => {
  Nprogress.done()
})
